<?php

namespace common\user\service;

use think\Model;
use think\Db;
use think\Validate;
use common\user\model\UserModel;
use common\user\model\ThirdPartyUserModel;
use think\Config;
use common\wechat\model\WechatUserModel;

/**
 * 用户接口,增改
 * 
 */
class PostService extends Model {

    /**
     * 后台增加用户
     * @param array $where 过滤条件
     * @return mixed
     */
    public function add($param = []) {
        if (!empty($param['role_id']) && is_array($param['role_id'])) {
            $role_ids = $param['role_id'];
            unset($param['role_id']);
            $validate = validate('/admin/worker/user');
            if (!$validate->check($param)) {
                $this->error = $validate->getError();
                return FALSE;
            } else {
                $param['user_pass'] = cmf_password($param['user_pass']);
                $result = DB::name('user')->insertGetId($param);
                if ($result !== false) {
                    //$role_user_model=M("RoleUser");
                    foreach ($role_ids as $role_id) {
                        if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                            $this->error = "为了网站的安全，非网站创建者不可创建超级管理员！";
                            return FALSE;
                        }
                        Db::name('RoleUser')->insert(["role_id" => $role_id, "user_id" => $result]);
                    }
                    return true;
                } else {
                    $this->error = "添加失败！";
                    return FALSE;
                }
            }
        } else {
            $this->error = "请为此用户指定角色！";
            return FALSE;
        }
    }

    /**
     * 后台修改用户
     * @param object $param 参数
     * @return mixed
     */
    public function editPost($request = object, $secen = 'edit') {
        $_param = $request->param();
        if (!empty($_param['role_id']) && is_array($_param['role_id'])) {
            if (empty($_param['user_pass'])) {
                unset($_param['user_pass']);
            } else {
                $_param['user_pass'] = cmf_password($_param['user_pass']);
            }
            $role_ids = $request->param('role_id/a');
            unset($_param['role_id']);

            $validate = validate('/admin/worker/user');

            if (!$validate->scene($secen)->check($_param)) {
                // 验证失败 输出错误信息
                $this->error = $validate->getError();
                return FALSE;
            } else {
                $result = DB::name('user')->update($_param);
                if ($result !== false) {
                    $uid = $request->param('id', 0, 'intval');
                    DB::name("RoleUser")->where(["user_id" => $uid])->delete();
                    foreach ($role_ids as $role_id) {
                        if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                            $this->error = "为了网站的安全，非网站创建者不可创建超级管理员！";
                            return FALSE;
                        }
                        DB::name("RoleUser")->insert(["role_id" => $role_id, "user_id" => $uid]);
                    }
                    return true;
                } else {
                    $this->error = "保存失败！";
                    return FALSE;
                }
            }
        } else {
            $this->error = "请为此用户指定角色！";
            return FALSE;
        }
    }

    /**
     * 删除用户
     * @param object $param 参数
     * @return mixed
     */
    public function delete($request = object) {
        $id = $request->param('id', 0, 'intval');
        if ($id == 1) {
            $this->error = "最高管理员不能删除！";
            return FALSE;
        }

        if (Db::name('user')->delete($id) !== false) {
            Db::name("RoleUser")->where(["user_id" => $id])->delete();
            return true;
        } else {
            $this->error = "删除失败！";
            return FALSE;
        }
    }

    /**
     * 前台用户注册提交
     */
    public function Register($request = object, $is_validate = true) {


        $rules = [
            'captcha' => 'require',
            'code' => 'require',
            'password' => 'require|min:6|max:32',
        ];

        $isOpenRegistration = cmf_is_open_registration();

        if ($isOpenRegistration) {
            unset($rules['code']);
        }

        $validate = new Validate($rules);
        $validate->message([
            'code.require' => '验证码不能为空',
            'password.require' => '密码不能为空',
            'password.max' => '密码不能超过32个字符',
            'password.min' => '密码不能小于6个字符',
            'captcha.require' => '验证码不能为空',
        ]);

        $data = $request->post();
        if (!$validate->check($data)) {
            $this->error = $validate->getError();
            return FALSE;
        }

        $captchaId = empty($data['_captcha_id']) ? '' : $data['_captcha_id'];
        if (!cmf_captcha_check($data['captcha'], $captchaId)) {
            $this->error = '验证码错误';
            return FALSE;
        }
        if (!$isOpenRegistration) {
            $errMsg = cmf_check_verification_code($data['username'], $data['code']);
            if (!empty($errMsg)) {
                $this->error = $errMsg;
                return FALSE;
            }
        }







        $register = new UserModel();
        $user['user_pass'] = $data['password'];
        if (Validate::is($data['username'], 'email')) {
            $user['user_email'] = $data['username'];
            $log = $register->register($user, 3);
        } else if (cmf_check_mobile($data['username'])) {
            $user['mobile'] = $data['username'];
            $log = $register->register($user, 2);
        } else {
            $log = 2;
        }

        switch ($log) {
            case 0:
                return TRUE;
                break;
            case 1:
                $this->error = "您的账户已注册过";
                return FALSE;
                break;
            case 2:
                $this->error = "您输入的账号格式错误";
                return FALSE;
                break;
            default :
                $this->error = '未受理的请求';
                return FALSE;
        }
    }

    /**
     * 前台用户注册提交
     */
    public function Register_third($request = object, $type = '') {
        $post = $request->param();
        $user_data = [];
        $data = [];
        //检查第三方表
        // 先检查下,是哪个第三方
        switch ($post['type']) {
            case 1:
//                $config = Config::get('wechat');
                if (empty($type)) {
                    $config = cmf_is_wechat() ? Config::get('wechat.Web') : Config::get('wechat.Official');
                } else {
                    $config = Config::get('wechat.' . $type);
                }

                $app_id = $config['appid'];
                $user_data['sex'] = empty($post['sex']) ? 0 : $post['sex'];
                $user_data['user_nickname'] = $post['nickname'];
                $user_data['avatar'] = $post['headimgurl'];
                $user_data['user_login'] = 'wx_' . time() . rand(1000, 9999);
                $device_type = 'wechat';
                $data['nickname'] = $post['nickname'];
                $data['app_id'] = $app_id;
                $data['last_login_ip'] = $post['last_login_ip'];
                $data['openid'] = $post['openid'];
                $data['union_id'] = $post['unionid'];
                $data['type'] = $post['type'];
                break;

            default:
                break;
        }

        $ThirdPartyUser = new ThirdPartyUserModel;
        $where = [];
        $where['app_id'] = $app_id;
        $where['openid'] = $post['openid'];
        $where['type'] = $post['type'];
        if (isset($post['unionid']) && !empty($post['unionid'])) {
            $where['union_id'] = $post['unionid'];
        }
        $user = new UserModel();
        $third_user_info = $ThirdPartyUser::get($where);
        if (!empty($user_info)) {
            // 有用户了.说明已经注册过了.但这有个问题.user_id是绑定的哪个用户.这个地方如果绑定了用户.就是父id为!=0
            // 父id = -1 说明是子帐号,同期绑定的作用范围也会有一个,其实是2个微信号共用一个第三方用户id,但都是这个用户,只是作用范围不同.
//            
//            $where=[];
//            $where['id']=$third_user_info['user_id'];
//            $user_info= $user::get($where);
            return $third_user_info['id'];
        }
        // 没注册过.就需要注册
        // 先注册个通行证,然后在添加第三方帐号信息

        $user_data['parent_id'] = -1;
        $user_data['score'] = 0;
        $user_data['coin'] = 0;
        $user_data['balance'] = 0;
        $user_data['user_status'] = 1;
        $user_data['user_pass'] = cmf_random_string(8);

        $userId = $user->register($user_data, 1, $device_type);
        // 注册第三方帐号
        $data['user_id'] = $userId;
        $data['last_login_time'] = time();
        $data['status'] = 1;
        $ThirdPartyUser->data($data)->isUpdate(false)->allowField(true)->save();
    }

    /**
     * 后台修改用户
     * @param object $param 参数
     * @return mixed
     */
    public function edit_third($OauthUserinfo = []) {
        $UserWx = new WechatUserModel();

        $data = $OauthUserinfo;
        $ret = $UserWx->isUpdate(true)->allowField(true)->save($data);
        if (!empty($ret)) {
            // 代表有内容更新.需要更新下其他相关表
            // 第三方表
            $ThirdPartyUser = new ThirdPartyUserModel();
            $where = [];
            $where['app_id'] = $OauthUserinfo['app_id'];
            if (!empty($OauthUserinfo['union_id'])) {
                $where['union_id'] = $OauthUserinfo['union_id'];
            }
            $where['openid'] = $OauthUserinfo['openid'];
            $third_user_info = $ThirdPartyUser::get($where);

            $data = $where;
            $data['id'] = $third_user_info['id'];
            $data['nickname'] = $OauthUserinfo['nickname'];
            $ThirdPartyUser->isUpdate(true)->allowField(true)->save($data);
            // 更新用户表
            $User = new UserModel();
            $data = [
                'id' => $third_user_info['user_id'],
                'user_nickname' => $OauthUserinfo['nickname'],
                'sex' => $OauthUserinfo['sex'],
                'avatar' => $OauthUserinfo['headimgurl'],
                'last_login_ip' => get_client_ip(0, true),
            ];
            $User->isUpdate(true)->allowField(true)->save($data);
        }
    }

}
